package co.baiku.boot.rabbit;

import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
public class RabbitMQSender {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private AsyncRabbitTemplate asyncRabbitTemplate;

    /**
     * 发送延迟消息
     *
     * @param exchange   交换机
     * @param routingKey 路由
     * @param message    消息体
     */
    public void send(String exchange, String routingKey, String message) {
        this.rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 发送延迟消息
     *
     * @param exchange   交换机
     * @param routingKey 路由
     * @param message    消息体
     * @param delay      延迟,毫秒
     */
    public void sendLazy(String exchange, String routingKey, Object message, Integer delay) {
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(asyncRabbitTemplate);
        rabbitTemplate.setReturnCallback(asyncRabbitTemplate);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().replaceAll("-", ""));
        //发送消息时指定 header 延迟时间
        rabbitTemplate.convertAndSend(exchange, routingKey, message,
                dataMessage -> {
                    dataMessage.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    dataMessage.getMessageProperties().setExpiration(String.valueOf(delay));
                    return dataMessage;
                }, correlationData);
    }

}